/* -----------------------------------------------------------------------------
 * PROJECT    : lwf_web
 * FILE       : CheckURLFilter.java
 *
 * HISTORY:
 * Date          Author                        Description
 * ----------------------------------------------------------------------------- 
 * May 21, 2012  MyCodeTalks			       Created
 */

package net.lwf.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import net.lwf.exception.AppException;
import net.lwf.exception.ExceptionUtil;
import net.lwf.web.constant.IWebConstant;

/**
 * Refer: 
 * 1. http://www.coderanch.com/t/210679/JSF/java/Exception-Handling-error-page
 * 2. http://www.tutorialspoint.com/servlets/servlets-exception-handling.htm
 *
 */
public class CheckURLFilter implements Filter {
	
	private Map<String, String> mapUris = new HashMap<String, String>();

	public void destroy() {
	}

	public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse,
			FilterChain filterchain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletrequest;
		
		String uri = request.getRequestURI();
		if(this.mapUris.containsKey(uri)) {
			AppException aex = new AppException("... Illegal URI " + uri + " requested");
			request.setAttribute(IWebConstant.EXCEPTION_ID, aex.getUniqueID());
			ExceptionUtil.logAndThrowException(CheckURLFilter.class, aex);
		}
		else {
			filterchain.doFilter(servletrequest, servletresponse);
		}	
	}

	public void init(FilterConfig filterconfig) throws ServletException {
		this.mapUris.put("/lwf/logs/", "/lwf/logs/");
		this.mapUris.put("/lwf/logs", "/lwf/logs");
		this.mapUris.put("/lwf/pdf/", "/lwf/pdf/");
		this.mapUris.put("/lwf/pdf", "/lwf/pdf");
		this.mapUris.put("/lwf/image/", "/lwf/image/");
		this.mapUris.put("/lwf/image", "/lwf/image");
	}
}
